<?php

require_once 'Vega/View.php';

class Vega_View_Cache extends Vega_View
{
    /**
     * Global cache engine. Use by every view object
     *
     * @var Vega_Cache_Output
     */
    protected static $_globalCacheManager = null;

    /**
     * Cache engine
     *
     * @var Vega_Cache_Output
     */
    protected $_cacheManager = null;


    protected $_cachePrefix = null;

    /**
     * Set the global cache engine for every view object
     * @param Vega_Cache_Engine_Abstract $cache
     */
    public static function setGlobalCache(Vega_Cache_Output $cache)
    {
        self::$_globalCacheManager = $cache;

    }

    public function __construct(Vega_Loader $loader, $cachePrefix)
    {
        parent::__construct($loader);
        $this->_cacheManager = self::$_globalCacheManager;
        $this->_cachePrefix = $cachePrefix;
    }

    /**
     *
     */
    protected function _render($templateFile, &$data, $options = array())
    {
        $output = parent::_render($templateFile, &$data);

        if (isset($options['cache']))
        {
            $cache = intval($options['cache']);

            if (!isset($options['cache_name']))
            {
                $cacheName = $this->_cacheManager->getCacheKeyByUri($templateFile);
            }
            else
            {
                $cacheName = $options['cache_name'];
            }

            if ($cache > 0)
            {
                $this->_cacheManager->save($cacheName, $output, $cache, $options[]);
            }
        }
    }

    /**
     * Sets cache engine
     *
     * @param Vega_Cache_Engine_Abstract $cache
     */
    public function setCacheManager(Vega_Cache_Output $cache)
    {
        $this->_cacheManager = $cache;
        return $this;
    }

    /**
     *
     * @return Vega_Cache_Output
     */
    public function getCacheManager()
    {
        return $this->_cacheManager;
    }

    /**
     * Render a cached page
     *
     * @param string $data
     * @param array $options
     */
    public function renderCache($cacheKey)
    {
        $data = $this->_cacheManager->load($cacheKey, false, $this->_cachePrefix);

        $options = &$data['options'];
        
        if ($options['need_layout'])
        {
            if (isset($options['layout_dir']))
            {
                $this->setLayoutDir($options['layout_dir']);
            }

            if (isset($options['skin_name']))
            {
                $this->setSkinName($options['skin_name']);
            }

            if (isset($options['layout_name']))
            {
                $this->setSkinName($options['layout_name']);
            }

            $data['output'] = $this->renderLayout($data['output']);
        }
        return $data['output'];
    }
}
